package com.lanxin.jet.controllers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@PropertySource("classpath:config.properties")
public class MobileController {

    @Value("${jet.mobile.path}")
    private String resourcePath;

    /**
     * 页面模拟器
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/m/**")
    public String renderPage(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String pageContent = "Page Not Found.";
        String url = request.getRequestURI();
        String pageFile = "";
        if (url.length() > 3) {
            pageFile = resourcePath + url.substring(3) + ".html";
        }
        File file = new File(pageFile);
        StringBuilder content = null;
        if (file.exists()) {
            content = loadFile(pageFile);
        }
        if (content != null && content.length() > 0) {
            //加载资源文件
            Matcher matcher = Pattern.compile("<asset>([\\w\\-\\.]*?)<\\/asset>").matcher(content.toString());
            while (matcher.find()) {
                String resourceFile = matcher.group(1);
                String extName = resourceFile.substring(resourceFile.lastIndexOf(".") + 1);
                if (extName.equals("css")) {
                    stringBuilderReplace(content, matcher.group(0), "<link href=\"/mobile/load/"+resourceFile+"\" rel=\"stylesheet\" />");
                } else if (extName.equals("js")) {
                    stringBuilderReplace(content, matcher.group(0), "<script type=\"text/javascript\" src=\"/mobile/load/" + resourceFile + "\"></script>");
                }
            }
            //注入页面参数
            String params = request.getQueryString();
            if (params != null && !params.isEmpty()) {
                String[] paramList = params.split("&");
                for (String item : paramList) {
                    int j = item.indexOf("=");
                    if (j != -1) {
                        stringBuilderReplace(content, "#" + item.substring(0, j) + "#", item.substring(j + 1));
                    }
                }
            }
            pageContent = content.toString();
            pageContent = pageContent.replaceAll("app-page:back", "javascript:history.back()");
            pageContent = pageContent.replaceAll("app-page:", "/m/");
            pageContent = pageContent.replaceAll("app-local:", "/mobile/load/res/");
        }
        return pageContent;
    }

    /**
     * 加载资源文件
     * @param request
     * @param response
     */
    @RequestMapping("/mobile/load/**")
    public void renderResource(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        if (uri.length() > 12) {
            String path = uri.substring(13);
            File file = new File(resourcePath + path);
            if (file.exists()) {
                byte[] buffer = new byte[2048];
                FileInputStream fileInputStream;
                BufferedInputStream bufferedInputStream;
                OutputStream outputStream;
                try {
                    fileInputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    outputStream = response.getOutputStream();
                    int i = 0;
                    while((i = bufferedInputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, i);
                    }
                    outputStream.close();
                    bufferedInputStream.close();
                    fileInputStream.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }
        
    }

    /**
     * 从资源文件中加载内容
     * @param filePath
     * @return
     */
    private StringBuilder loadFile(String filePath) {
        StringBuilder content = new StringBuilder();
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * StringBuilder字符串替换
     * @param stringBuilder
     * @param search
     * @param target
     */
    private void stringBuilderReplace(StringBuilder stringBuilder, String search, String target) {
        int len = search.length();
        int start;
        while ((start = stringBuilder.indexOf(search)) > -1) {
            stringBuilder.replace(start, start + len, target);
        }
    }
}